/**
 * 
 */
package com.ssm.exception;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.json.JSONUtils;
/**
 * spring mvc  异常拦截类(SSM)
 * @author 危文涛<245108903@qq.com>
 * @version 2016年2月25日 上午11:40:29
 *
 */
public class SSMExceptionHandler implements HandlerExceptionResolver {

	private Integer defaultTimeSeconds;
	
	
	public void setDefaultTimeSeconds(Integer defaultTimeSeconds) {
		this.defaultTimeSeconds = defaultTimeSeconds;
	}

	private String defaultErrorViewName;
	

	public void setDefaultErrorViewName(String defaultErrorViewName) {
		this.defaultErrorViewName = defaultErrorViewName;
	}


	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		
		String requestType = request.getHeader("X-Requested-With");
		if(requestType!=null&&requestType.equals("XMLHttpRequest"))//ajax请求
		{
			if(ex instanceof SsmException) //SsmException
			{
				
			}
			else if(ex instanceof WebException) //WebException
			{
				
			}
			else {//其他Exception
				
			}
			try {
				Map<String,String> map=new HashMap<String,String>();
				map.put("success","0");
				map.put("message",ex.getMessage());
				response.getWriter().println(JSONUtils.toJSONString(map));
				response.getWriter().flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return new ModelAndView();
		}
		else//普通请求
		{
			ModelAndView mView=new ModelAndView(defaultErrorViewName);
			System.out.println("ex:"+(ex instanceof WebException));
			if(ex instanceof SsmException) //SsmException
			{
				SsmException ssmException=(SsmException)ex;
				if(ssmException.getRedirect()!=null)
					mView.addObject("redirect",ssmException.getRedirect());
				if(ssmException.getTimeSeconds()!=null)
					defaultTimeSeconds=ssmException.getTimeSeconds();
				mView.addObject("timeSeconds",defaultTimeSeconds);
				mView.addObject("message",ex.getMessage());
				return mView;
			}
			else if(ex instanceof WebException) //WebException
			{
				mView.addObject("timeSeconds",3);
				mView.addObject("message",ex.getMessage());
				return mView;
			}
			else {//其他Exception
				mView.addObject("timeSeconds",3);
				mView.addObject("message",ex.getMessage()+"wdadqdwq");
				return mView;
			}
		}
		
		
	}

}

